package com.gao.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * 求和计算的任务
 * 如何使用forkJoin
 * 1、 forkJoinPool 来执行
 * 2、 新建计算任务 forkJoinPool.execute(ForkJoinTask task)
 * 3、 计算类要继承ForkJoinTask
 */

public class ForkJoinDemo extends RecursiveTask<Long> {
    private long start;
    private long end;
    //    临界值
    private long temp = 50000000L;

    public ForkJoinDemo(long start, long end) {
        this.start = start;
        this.end = end;
    }

    public static void main(String[] args) {

    }

//    计算方法
    @Override
    protected Long compute() {
        if ((end - start) < temp) {
            Long sum = 0L;
            for (Long i = start; i < end; i++) {
                sum += i;
            }
            return sum;
        }else {
//            分支合并计算 forkJoin
            long middle = (start + end) / 2;

            ForkJoinDemo task1 = new ForkJoinDemo(start,middle);
//            拆分任务，把任务压入线程队列
            task1.fork();
            ForkJoinDemo task2 = new ForkJoinDemo(middle + 1,end);
            task2.fork();

            return task1.join() + task2.join();
        }
    }
}
